package com.zhu.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.zhu.pojo.entity.Result;
import com.zhu.pojo.entity.User;
import com.zhu.properties.JwtProperties;
import com.zhu.service.UserService;
import com.zhu.utils.JwtUtil;
import com.zhu.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.swing.plaf.synth.SynthTreeUI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    @GetMapping
    public String hello() {
        return "hello";
    }


    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        if (userService.register(username, password)) {
            return Result.success(username + " 注册成功");
        } else {
            return Result.error(username + " 已注册");
        }
    }

    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        User user = userService.login(username, password);
        if (user == null) {
            return Result.error(username + " 未注册");
        } else {
            if (DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())) {
                Map<String, Object> claims = new HashMap<>();
                claims.put("id", user.getId());
                claims.put("username", user.getUsername());
                String token = JwtUtil.createJWT(
                        jwtProperties.getAdminSecretKey(),
                        jwtProperties.getAdminTtl(),
                        claims);
                Map<String, Object> data = new HashMap<>();
                data.put(jwtProperties.getAdminTokenName(), token);
                return Result.success(username + " 登录成功", data);
            } else {
                return Result.error(username + " 密码错误");
            }
        }

    }

    @GetMapping("/userinfo")
    public Result<User> userInfo(@RequestHeader Map<String, String> headers) {
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        userService.update(user);
        return Result.success("用户信息更新成功");
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return Result.success("头像更新成功");
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params) {
        // 获取密码
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("缺少必要参数");
        }
        // 获取原始密码
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        // 比较原始密码
        String pwd = user.getPassword();
        if (!DigestUtils.md5DigestAsHex(oldPwd.getBytes()).equals(pwd)) {
            return Result.error("原密码错误");
        }
        if (!newPwd.equals(rePwd)) {
            return Result.error("两次密码输入不一致");
        }
        if (!newPwd.matches("^\\S{5,16}$")) {
            return Result.error("必须输入5~16位密码");
        }
        userService.updatePwd(newPwd);
        return Result.success("密码更新成功");
    }
}
